define(function (require, exports, module) {
    var angular = require("angular");
    var ui = require('ui');
    var util = require('util');
    require("angular-ui");
    require('service/ng_service/productTypeService');

    var urlPrefix = G_CONFIG.api_prefix + "qmyx/para-setting/";

    angular
        .module('ProjectCommissionRules', ['ngUI', 'ProductTypeService'])
        .service('brokerIdentities', ['$q', '$http', function ($q, $http) {
            /**
             * 所有身份数组
             */
            return function (cache) {
                if (typeof cache == 'undefined') {
                    cache = true;
                }

                var defer = $q.defer();

                $http.get(G_CONFIG.api_prefix + 'qmyx/broker/get-broker-identity-by-token', {cache: cache})
                    .success(function (res) {
                        if (res.retCode == 0) {

                            var data = res.data;
                            var item;
                            for (var i = 0; item = data[i]; i++) {
                                item.value = item.Value;
                                item.name = item.Text;
                            }

                            defer.resolve(data);
                        } else {
                            defer.reject();
                        }
                    })
                    .error(function () {
                        defer.reject();
                    });

                return defer.promise;
            };
        }])
        .service('usedIdentities', ['$q', '$http', function ($q, $http) {
            /**
             * 已用的身份数组
             */
            return function (proId, config) {
                config = config || {};
                var cache = config.cache;
                if (typeof cache == 'undefined') {
                    cache = false;
                }

                var defer = $q.defer();

                $http.get(urlPrefix + 'get-used-identity-data', {cache: cache, params: {proId: proId}})
                    .success(function (res) {
                        if (res.retCode == 0) {
                            var data = res.data;
                            var res = [];
                            var item;
                            for (var i = 0; item = data[i]; i++) {
                                res.push({value: item});
                            }
                            defer.resolve(res);
                        } else {
                            defer.reject();
                        }
                    })
                    .error(function () {
                        defer.reject();
                    });

                return defer.promise;
            };
        }])
        .service('usableIdentities', ['$q', 'usedIdentities', 'brokerIdentities', function ($q, usedIdentities, brokerIdentities) {
            /**
             * 可用的身份数组
             * @param {string} proId
             * @param {{usedIdentities:Array=,brokerIdentities:Array=}} data
             */
            return function (proId, data) {
                data = data || {};

                var defer = $q.defer();

                var usedIdentitiesCache = data.usedIdentities || [];

                $q.all([usedIdentities(proId), brokerIdentities()]).then(
                    function (resArr) {
                        var list = resArr[0];
                        var allIdentities = resArr[1];

                        var res = [];

                        var equalFunc = function (a, b) {
                            return a.value === b.value;
                        };
                        var item;
                        for (var i = 0; item = allIdentities[i]; i++) {
                            if (!util.inArray(item, list, equalFunc) && !util.inArray(item, usedIdentitiesCache, equalFunc) && item.Disabled != 1) {
                                res.push(item);
                            }
                        }

                        defer.resolve(res);
                    },
                    function () {
                        defer.reject();
                    }
                );

                return defer.promise;
            };
        }])
        .service('ruleDetail', ['$q', '$http', function ($q, $http) {
            return function (ruleId, config) {
                config = config || {};

                var cache = config.cache;
                if (typeof cache == 'undefined') {
                    cache = false;
                }

                var defer = $q.defer();

                $http.get(urlPrefix + 'get-bonus-rule-by-hpid', {cache: cache, params: {hpId: ruleId}})
                    .success(function (res) {
                        if (res.retCode == 0) {
                            var data = res.data;

                            var identityInfoAllMap = data.rule.identityInfo;
                            var identities = data.rule.identity.split(",");

                            var identityInfos = [];
                            var identity;
                            for (var i = 0; identity = identities[i]; i++) {
                                var identityName = identityInfoAllMap[identity];
                                if (identityName) {
                                    identityInfos.push({value: identity, name: identityName});
                                }
                            }
                            data.identityInfos = identityInfos;

                            var identityInfosAll = [];
                            for (var key in identityInfoAllMap) {
                                if (identityInfoAllMap.hasOwnProperty(key)) {
                                    identityInfosAll.push({
                                        value: key,
                                        name: identityInfoAllMap[key]
                                    });
                                }
                            }
                            data.identityInfosAll = identityInfosAll;

                            var content = data.rule.content;

                            var ruleTwo;
                            if (content && content.length > 0) {
                                ruleTwo = content[0].ruleTwo;
                            } else {
                                content = [];
                            }
                            data.rule.content = content;
                            if (!ruleTwo) {
                                ruleTwo = [
                                    {'Num': 1, 'Conditions': '条件', 'Proportion': 100}
                                ];
                            }
                            data.ruleTwo = ruleTwo;

                            defer.resolve(data);
                        } else {
                            defer.reject();
                        }
                    })
                    .error(function () {
                        defer.reject();
                    })

                return defer.promise;
            };
        }])
        .controller('CommissionRulesController', ['$scope', '$http', 'usableIdentities', '$timeout', 'ruleDetail', 'productTypeList',
            function ($scope, $http, usableIdentities, $timeout, ruleDetail, productTypeList) {
                $scope.curRule = null;
                $scope.setRuleSelected = function (rule) {
                    $scope.curRule = rule;
                };
                $scope.curRuleDetail = null;
                $scope.$watch('curRule', function () {
                    if ($scope.curRule) {
                        ruleDetail($scope.curRule.help_id).then(function (detail) {

                            if (detail.rule.content && detail.rule.content.length > 0) {
                                var ruleItem;
                                for (var i = 0; ruleItem = detail.rule.content[i]; i++) {
                                    if (ruleItem.CalcRule == 3) {
                                        var item;
                                        for (var j = 0; item = ruleItem.ruleOne[j]; j++) {
                                            item.LowerLimit = item.LowerLimit / 10000;
                                            item.HigherLimit = item.HigherLimit / 10000;
                                        }
                                    }
                                }
                            }

                            $scope.curRuleDetail = detail;

                            if (!detail.rule.content || detail.rule.content.length == 0) {
                                $scope.addRuleType();
                            }
                        })
                    } else {
                        $scope.curRuleDetail = null;
                        $scope.curRule = null;
                    }
                });

                $scope.calculateTypes = [
                    {name: "按比例计算", value: "1"},
                    {name: "固定计算", value: "2"},
                    {name: "区间计算", value: "3"}
                ];
                $scope.curCalculateTypeValue = $scope.calculateTypes[0].value;

                /**
                 * 新增规则弹层
                 * @param data
                 * @param dialog
                 * @param dialogScope
                 */
                $scope.showEditRule = function (data, dialog, dialogScope) {
                    dialogScope.loading = true;
                    usableIdentities($scope.curProjectId)
                        .then(function (list) {
                            dialogScope.brokerIdentities = list;
                            $timeout(function () {
                                dialog.reset();
                            });
                        })
                        .finally(function () {
                            dialogScope.loading = false;
                        });
                };

                /**
                 * 增加规则
                 * @param data
                 * @param dialog
                 * @param dialogScope
                 * @returns {boolean}
                 */
                $scope.addRule = function (data, dialog, dialogScope) {
                    var brokerIdentities = dialogScope.brokerIdentities;

                    var selectedIdentities = [];
                    var item;
                    for (var i = 0; item = brokerIdentities[i]; i++) {
                        if (item.selected) {
                            selectedIdentities.push(item.Value);
                        }
                    }

                    $http.post(urlPrefix + 'add-bonus-rule', {
                        'proId': $scope.curProjectId,
                        'ruleName': data.ruleName,
                        'identity': selectedIdentities.join(',')
                    })
                        .success(function (res) {
                            if (res.retCode) {
                                dialog.close();

                                $scope.data.rule_help.push({
                                    help_id: res.data.btHelpId,
                                    identity: selectedIdentities.join(','),
                                    rule_name: data.ruleName
                                });

                                $scope.setRuleSelected($scope.data.rule_help[$scope.data.rule_help.length - 1]);
                            }
                        });
                    return false;
                };

                /**
                 * 显示添加身份弹层
                 * @param data
                 * @param dialog
                 * @param dialogScope
                 */
                $scope.showAddIdentity = function (data, dialog, dialogScope) {
                    dialogScope.loading = true;
                    usableIdentities($scope.curProjectId, {usedIdentities: $scope.curRuleDetail.identityInfos})
                        .then(function (list) {
                            dialogScope.brokerIdentities = list;
                            $timeout(function () {
                                dialog.reset();
                            });
                        })
                        .finally(function () {
                            dialogScope.loading = false;
                        })
                };

                /**
                 * 新增身份
                 * @param data
                 * @param dialog
                 * @param dialogScope
                 */
                $scope.addIdentities = function (data, dialog, dialogScope) {
                    var brokerIdentities = dialogScope.brokerIdentities;
                    var selectedIdentities = [];
                    var item;
                    for (var i = 0; item = brokerIdentities[i]; i++) {
                        if (item.selected) {
                            selectedIdentities.push({value: item.Value, name: item.Text});
                        }
                    }

                    $scope.curRuleDetail.identityInfos = $scope.curRuleDetail.identityInfos.concat(selectedIdentities);
                    return true;
                };

                $scope.deleteIdentity = function (identity) {
                    util.removeFromArr(identity, $scope.curRuleDetail.identityInfos);
                };

                /**
                 * 编辑规则
                 * @param ruleItem
                 */
                $scope.editRuleName = function (ruleItem) {
                    $http.post(urlPrefix + 'edit-bonus-rule', {
                        'id': ruleItem.help_id,
                        'name': ruleItem.rule_name
                    })
                        .success(function (res) {
                            if (res.retCode == 0) {
                                var item;
                                for (var i = 0; item = $scope.data.rule_help[i]; i++) {
                                    if (item.help_id === ruleItem.help_id) {
                                        item.rule_name = ruleItem.rule_name;
                                        break;
                                    }
                                }

                                ui.showSucTip();
                            }
                        });
                };

                /**
                 * 删除规则
                 * @param ruleItem
                 */
                $scope.deleteRule = function (ruleItem) {
                    util.confirm('确定删除规则？', {
                        ok: function () {
                            $http.post(urlPrefix + 'del-bonus-rule', {'id': ruleItem.help_id})
                                .success(function (res) {
                                    if (res.retCode == 0) {
                                        update($scope.curProjectId).finally(function () {
                                            ui.showSucTip();
                                        });
                                    }
                                });
                        }
                    });
                };

                /**
                 * 新增类型
                 */
                $scope.addRuleType = function () {
                    var productType = "";
                    if ($scope.productTypeList && $scope.productTypeList.length > 0) {
                        productType = $scope.productTypeList[0].Text;
                    }

                    var defaultCalcRule = '1';
                    $scope.curRuleDetail.rule.content.push({
                        "CalcRule": defaultCalcRule,
                        "ProductType": productType,
                        "ruleOne": createRuleOne(defaultCalcRule)
                    });
                };

                /**
                 * 删除类型
                 */
                $scope.deleteRuleType = function (ruleItem) {
                    util.confirm('确定移除？', {
                        ok: function () {
                            util.removeFromArr(ruleItem, $scope.curRuleDetail.rule.content);
                            $scope.$applyAsync();
                        }
                    })
                };

                /**
                 * 新增区间规则
                 * @param rangeRules
                 */
                $scope.addRangeRule = function (rangeRules) {
                    rangeRules.push({"LowerLimit": 0, "HigherLimit": 100, "Amout": 1});
                };

                /**
                 * 移除区间规划
                 * @param {Object} rangeRule
                 * @param {Array} rangeRules
                 */
                $scope.deleteRangeRule = function (rangeRule, rangeRules) {
                    util.confirm('确定移除？', {
                        ok: function () {
                            util.removeFromArr(rangeRule, rangeRules);
                            $scope.$applyAsync();
                        }
                    })
                };

                /**
                 * @param {string} calcRule
                 * @returns {Object}
                 */
                function createRuleOne(calcRule) {
                    var ruleOne = null;
                    switch (calcRule) {
                        case '1':
                            ruleOne = {Percentage: 0, GuaranteesAmount: 1, CapAmount: 1};
                            break;
                        case '2':
                            ruleOne = {Amount: 1};
                            break;
                        case '3':
                            ruleOne = [{"LowerLimit": 0, "HigherLimit": 100, "Amout": 1}];
                            break;
                    }
                    return ruleOne;
                }

                /**
                 * @param obj
                 * @returns {string}
                 */
                function getFirstKey(obj) {
                    if (obj) {
                        for (var key in obj) {
                            if (obj.hasOwnProperty(key)) {
                                return key;
                            }
                        }
                    }
                    return null;
                }

                /**
                 * 变更计算方式
                 * @param ruleItem
                 */
                $scope.changeCalculateType = function (ruleItem) {
                    var calcRule = ruleItem.CalcRule;
                    var ruleOneNew = createRuleOne(calcRule);

                    //判断改变类型受否有变动
                    if (!ruleItem.ruleOne || getFirstKey(ruleItem.ruleOne) !== getFirstKey(ruleOneNew)) {
                        ruleItem.ruleOne = ruleOneNew;
                    }
                };

                /**
                 * 增加佣金笔数
                 * @param commissons
                 */
                $scope.addCommission = function (commissons) {
                    var proportion = 100;
                    var num = 1;
                    if (commissons) {
                        var item;
                        for (var i = 0; item = commissons[i]; i++) {
                            proportion -= item.Proportion;
                        }

                        if (proportion < 0) {
                            proportion = 0;
                        }

                        num = commissons.length + 1;
                    }
                    commissons.push({'Num': num, 'Conditions': '条件', 'Proportion': proportion});
                };

                /**
                 * 删除佣金笔数
                 * @param commisson
                 * @param commissons
                 */
                $scope.deleteCommission = function (commisson, commissons) {
                    util.confirm('确定删除', {
                        ok: function () {
                            util.removeFromArr(commisson, commissons);

                            var item;
                            for (var i = 0; item = commissons[i]; i++) {
                                item.Num = i + 1;
                            }

                            $scope.$applyAsync();
                        }
                    });
                };

                /**
                 * 保存规则
                 */
                $scope.saveRule = function (form) {
                    //表单校验
                    var formName = form.$name;
                    for (var fieldName in form) {
                        if (form.hasOwnProperty(fieldName) && fieldName && fieldName.indexOf('$') !== 0) {
                            if (form[fieldName].$invalid) {
                                var $field = $('form[name=' + formName + '] [name=' + fieldName + ']');
                                setTimeout(function () {
                                    $field.focus();
                                }, 0);
                                break;
                            }
                        }
                    }
                    if (!form.$valid) {
                        return;
                    }

                    var data = $scope.data;

                    var postData = {
                        'proId': $scope.curProjectId,
                        'jyts': data.jyts.value,
                        'jytsId': data.jyts.id,
                        'dkyj': data.jy.ShowHouseBonus,
                        'rcyj': data.jy.IdentificationChipsBonus,
                        'yqyj': data.jy.InviteBrokerDealBonus,
                        'fftj': data.fftj.paravalue,
                        'fftjId': data.fftj.id
                    };

                    var postRules = [];
                    var identityArr = [];
                    if ($scope.curRuleDetail) {
                        var rules = angular.copy($scope.curRuleDetail.rule.content);
                        var item;
                        for (var i = 0; item = rules[i]; i++) {
                            var ruleOne = item['ruleOne'];
                            var calcRule = item['CalcRule'];
                            if (calcRule == 3) {
                                var item1;
                                for (var j = 0; item1 = ruleOne[j]; j++) {
                                    item1.LowerLimit = item1.LowerLimit * 10000;
                                    item1.HigherLimit = item1.HigherLimit * 10000;
                                }
                            }
                            postRules.push({
                                'CalcRule': calcRule,
                                'ProductType': item['ProductType'],
                                'ruleOne': ruleOne,
                                'ruleTwo': $scope.curRuleDetail.ruleTwo
                            });
                        }

                        var item;
                        for (var i = 0; item = $scope.curRuleDetail.identityInfos[i]; i++) {
                            identityArr.push(item.value);
                        }

                        postData['helpId'] = $scope.curRule.help_id;
                        postData['identity'] = identityArr.join(',');
                        postData['bonusRule'] = JSON.stringify({'BonusRule': postRules});
                    }

                    $http.post(urlPrefix + ($scope.curRuleDetail ? 'save-bonus-rule' : 'save-bonus-rule-two'), postData)
                        .success(function (res) {
                            if (res.retCode == 0) {
                                ui.showSucTip();
                            }
                        });
                };

                var update = function (projectId) {
                    productTypeList(projectId).then(function (productTypes) {
                        $scope.productTypeList = [{Text: '全部', Value: 'all'}].concat(productTypes);
                    });

                    $scope.loading = true;
                    return $http
                        .get(urlPrefix + "get-bonus-rule", {params: {proId: projectId}})
                        .success(function (res) {
                            if (res.retCode == 0) {
                                var data = res.data;

                                data.jy.ShowHouseBonus = parseFloat(data.jy.ShowHouseBonus);
                                data.jy.IdentificationChipsBonus = parseFloat(data.jy.IdentificationChipsBonus);
                                data.jy.InviteBrokerDealBonus = parseFloat(data.jy.InviteBrokerDealBonus);

                                $scope.data = data;

                                if ($scope.data.rule_help && $scope.data.rule_help[0]) {
                                    $scope.setRuleSelected($scope.data.rule_help[0]);
                                } else {
                                    $scope.setRuleSelected(null);
                                }
                            }
                        })
                        .finally(function () {
                            $scope.loading = false;
                        })
                };

                $scope.$watch('curProjectId', function () {
                    if ($scope.curProjectId) {
                        update($scope.curProjectId);
                    }
                });
            }])
});